import apiClient from '@/api/apiClient';

export interface PaymentOption {
  rule_id: number;
  price: number;
  pay_type: number;
  plat_type: number;
  diamond_amount: number;
  diamond_desc: string;
  apple_product_id: string | null;
  corner: string;
  diamond_extra_num: number;
}

export const fetchPaymentOptions = async (): Promise<PaymentOption[]> => {
  try {
    const response = await apiClient.get("/finance/pay/rules", { params: { platform: 4} });
    // response 实际为 data，itemlist 在 data 下
    return response.data.itemlist.map((item: any) => ({
      rule_id: item.rule_id,
      price: item.price,
      diamond_amount: item.diamond_amount,
      diamond_desc: item.diamond_desc,
      apple_product_id: item.apple_product_id,
      corner: item.corner,
      diamond_extra_num: item.diamond_extra_num,
    }));
  } catch (error) {
    console.error('Failed to fetch payment options:', error);
    throw error;
  }
};

export interface RechargeParams {
  user_id?: number;
  openid: string;
  phone: number;
  rule_id: number;
  pay_type: number;
  plat_type: number;
  code?: string;
  custom_price?: number;
  recharge_type?: number;
}

export interface WechatPayParams {
  appId: string;
  timeStamp: string;
  nonceStr: string;
  package: string;
  signType: string;
  paySign: string;
}

export interface RechargeResponse {
  code: number;
  msg: string;
  data: {
    pay_params?: WechatPayParams;
    mweb_url?: string; // H5支付的跳转链接
    order_id?: string;
    [key: string]: any;
  };
}

export const submitRecharge = async (params: RechargeParams): Promise<RechargeResponse> => {
  try {
    // 获取当前URL作为回调地址
    const currentUrl = typeof window !== 'undefined' ? window.location.href : '';
    const callbackUrl = new URL(currentUrl);
    
    // 添加当前路径作为回调，微信支付完成后会跳回该页面
    const finalParams = {
      ...params,
      return_url: callbackUrl.pathname + callbackUrl.search, // 支付成功后的回调地址
    };
    
    console.log('提交充值请求：', finalParams);
    const response = await apiClient.post(
      "/finance/pay/chhWxpub/do",
      finalParams
    );
    console.log('充值响应：', response);
    
    // apiClient已经在拦截器中处理了response.data的返回，所以这里直接返回
    return response as unknown as RechargeResponse;
  } catch (error) {
    console.error('充值请求失败:', error);
    throw error;
  }
};
